package com.itcast.util.Dao;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;


public class DaoUtils {

	public static <T> List<Predicate> getPredicateList(
			LinkedHashMap<PredicateDate, PredicateType> Predicates,
			CriteriaBuilder criteriaBuilder, Root<T> entity) {
		List<Predicate> predicateList = new ArrayList<Predicate>();
		for (PredicateDate key : Predicates.keySet()) {
			switch (Predicates.get(key)) {
			case GREATERTHAN:
				predicateList.add(criteriaBuilder
						.gt(entity.<Integer> get(key.getPredicateName()),
								(Integer) key.getPredicateValue()));
				break;
			case EQUAL:
				predicateList.add(criteriaBuilder.equal(entity.get(key
						.getPredicateName()), key.getPredicateValue()));
				break;
			case LESSTHAN:
				predicateList.add(criteriaBuilder
						.lt(entity.<Integer> get(key.getPredicateName()),
								(Integer) key.getPredicateValue()));
				break;
			case LIKE:
				predicateList
						.add(criteriaBuilder.like(entity.<String> get(key
								.getPredicateName()), (String) key
								.getPredicateValue()));
				break;
			}
		}
		return predicateList;
	}

	public static <T> List<Order> getOrderList(
			LinkedHashMap<String, OrderBy> orders,
			CriteriaBuilder criteriaBuilder, Root<T> entity) {
		List<Order> orderList = new ArrayList<Order>();
		for (String key : orders.keySet()) {
			switch (orders.get(key)) {
			case ASC:
				orderList.add(criteriaBuilder.asc(entity.get(key)));
				break;
			case DESC:
				orderList.add(criteriaBuilder.desc(entity.get(key)));
				break;
			}
		}
		return orderList;
	}

}
